package com.yjb.tenet.boot.system.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.yjb.tenet.boot.common.pojo.ResponseResult;
import com.xingyuv.captcha.model.vo.CaptchaVO;
import com.xingyuv.captcha.service.CaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 验证码相关
 * @author yinjinbiao
 * @create 2022/4/27 15:25
 */
@Slf4j
@RequestMapping("/system/captcha")
@RestController
public class CaptchaController {

	@Resource
	private CaptchaService captchaService;

	/**
	 * 获取验证码参数
	 * @param data
	 * @param request
	 * @return
	 */
	@SaIgnore
	@PostMapping({"/get"})
	public ResponseResult get(@RequestBody CaptchaVO data, HttpServletRequest request) {
		assert request.getRemoteHost() != null;
		data.setBrowserInfo(getRemoteId(request));
		return ResponseResult.ok(captchaService.get(data));
	}

	/**
	 * 校验验证码是否正确
	 * @param data
	 * @param request
	 * @return
	 */
	@SaIgnore
	@PostMapping("/check")
	public ResponseResult check(@RequestBody CaptchaVO data, HttpServletRequest request) {
		data.setBrowserInfo(getRemoteId(request));
		return ResponseResult.ok(captchaService.check(data));
	}

	public static String getRemoteId(HttpServletRequest request) {
		String ip = ServletUtil.getClientIP(request);
		String ua = request.getHeader("user-agent");
		if (StrUtil.isNotBlank(ip)) {
			return ip + ua;
		}
		return request.getRemoteAddr() + ua;
	}


}
